<?php

namespace App\Http\Controllers\Web;

use App\Models\Orders;
use App\Models\Goods;
use App\Models\GoodType;
use App\Models\WalletLogs;
use App\Models\Members;
use App\Models\MemberLevel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Auth;

class OrderController extends Controller
{
    public $result = array("status"=>0,'msg'=>'请求成功','data'=>"");

    /**
     * 列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
        	
        	$sortName = $request->post("sortName");    //排序列名
			$sortOrder = $request->post("sortOrder");   //排序（desc，asc）
			$pageNumber = $request->post("pageNumber");  //当前页码
			$pageSize = $request->post("pageSize");   //一页显示的条数
			$start = ($pageNumber-1)*$pageSize;   //开始位置
			$search = $request->post("search",'');  //搜索条件
			
			$total = Orders::where('is_del', '=',0)->where("uid","=",auth('web')->user()->id);
			$rows = Orders::where('is_del', '=',0)->where("uid","=",auth('web')->user()->id);
			
	        if(trim($search)){
	        	$total->where(function ($query) use ($search) {
                    $query->where('title', 'LIKE', '%' . $search . '%');
                });
	        	$rows->where(function ($query) use ($search) {
                    $query->where('title', 'LIKE', '%' . $search . '%');
                });
	        }
	        
	        $data['total'] = $total->count();
	        $data['rows'] = $rows->skip($start)->take($pageSize)
					        ->orderBy($sortName, $sortOrder)
					        ->get();
	        
	        foreach ($data['rows'] as $v){
                $v->dlprice =  number_format($v->price*$v->discount/100,2);
            }
	        
	        return response()->json($data);
        }
        return view('web.orders.index');
    }

    /**
     * 提交订单
     *
     */
    public function submitOrder(Request $request)
    {
        if ($request->ajax()) {
        	
            $id = $request->input("id");
            $amount = $request->input("amount");
            $goods_type_name = $request->input("goods_type_name");
		
            $goods = Goods::find((int)$id);
            $level = MemberLevel::find((int)auth('web')->user()->level);
			
			//判断是否有商品规格
			if(trim($goods_type_name)=="初始版"){
				if($goods->price_type == 1){
	                $agentPrice = $goods->price;
	            }elseif($goods->price_type == 0){
	                $agentPrice = round($goods->price*$level->discount/100,2);
	            }
	            $goods_price = $goods->price;  //单价
			}else{
				
				$arr = json_decode($goods->goods_version,true);
				foreach($arr as $k=>$v){
		        	if($v['goods_version']==trim($goods_type_name)&&$goods->price_type == 1){
		        		$agentPrice = $v['originalPrice'];
		        		$goods_price = $v['originalPrice'];  //单价
		        	}else if($v['goods_version']==trim($goods_type_name)&&$goods->price_type == 0){
		        		$agentPrice = round($v['originalPrice']*$level->discount/100,2);
		        		$goods_price = $v['originalPrice'];  //单价
		        	}
		        }
			}
            
            if($goods->price_type == 1){
            	$discount = 100;
            }else{
            	$discount = $level->discount;
            }
            
            $order["order_sn"] = $this->getOrderSn();
            $order["title"] = $goods->goods_name.'('.$goods_type_name.')';
            $order["type"]  = $goods->goods_type;
            $order["uid"]   = auth('web')->user()->id;
            $order["uname"]  = auth('web')->user()->name;
            $order["price"]     = $goods_price;  //单价
            $order["amount"]    = $amount;
	        $order["submitter"]    = Auth::guard('web')->user()->name;
            $order["total_price"] = round($amount*$agentPrice,2);
            
            $order["discount"] = $discount;
            $order["long"] = $goods->long;
            //0:余额   1:赠送金
            $order["pay_type"] = $request->input("pay_type");
            //入库
            $res_id = Orders::insertGetId($order);

            if(!$res_id){
                $this->result["status"] = 1;
                $this->result["msg"] = "下单失败,稍后重试！";
                return response()->json($this->result);
            }

            $this->payOrder($res_id,$order);
            return response()->json($this->result);
        }
    }
    /**
     * 扣款
     * @return json
     */
    public function payOrder($id,$order)
    {

        if(!is_numeric($order["pay_type"])){
            $this->result["status"] = 1;
            $this->result["msg"] = "参数错误！";
            return $this->result;
        }

        //0:余额   1:赠送金
        if($order["pay_type"] == 0){
            //余额支付
            $donation_amount = auth('web')->user()->wallet - $order["total_price"];
		
            if($donation_amount < 0){
                $this->result["status"] = 1;
                $this->result["msg"] = "余额不足,请选择其他支付方式或联系客服充值！";
                return $this->result;
            }

            $log["uid"] = auth('web')->user()->id;
            $log["type"] = 9;
            $log["money"] = '-'.$order["total_price"];
            $log["wallet"] = $donation_amount;
            $log["remarks"] = "";
            $log["operation"] = "余额消费￥".$order["total_price"].",商品名称：".$order["title"].",订单号：".$order['order_sn'];
            $log["created_at"] = Carbon::now()->toDateTimeString();
            $log["updated_at"] = Carbon::now()->toDateTimeString();
            WalletLogs::insertGetId($log);
            
            $user["wallet"] = $donation_amount;
            Members::where("id","=",auth('web')->user()->id)->update($user);
            Orders::where("id","=",$id)->update(array("status"=>0,"pay_status"=>1,"pay_time"=>time(),"pay_type"=>2));
            return $this->result;

        }elseif($order["pay_type"] == 1){
            //赠送金支付
            $donation_amount = auth('web')->user()->donation_amount - $order["total_price"];

            if($donation_amount < 0){
                $this->result["status"] = 1;
                $this->result["msg"] = "赠送金不足,请选择其他支付方式或联系客服充值！";
                return $this->result;
            }

            $log["uid"] = auth('web')->user()->id;
            $log["type"] = 3;
            $log["money"] = '-'.$order["total_price"];
            $log["wallet"] = $donation_amount;
            $log["remarks"] = "";
            $log["operation"] = "赠送金消费￥".$order["total_price"].",商品名称：".$order["title"].",订单号：".$order['order_sn'];
            $log["created_at"] = Carbon::now()->toDateTimeString();
            $log["updated_at"] = Carbon::now()->toDateTimeString();
            WalletLogs::insertGetId($log);
            
            $user["donation_amount"] = $donation_amount;
            Members::where("id","=",auth('web')->user()->id)->update($user);
            Orders::where("id","=",$id)->update(array("status"=>0,"pay_status"=>1,"pay_time"=>time(),"pay_type"=>3));
            return $this->result;

        }
        $this->result["status"] = 1;
        $this->result["msg"] = "参数错误！";
        return $this->result;
//        if(auth('web')->user()->donation_amount >= $order["total_price"]){
//            //赠送金支付
//            $donation_amount = auth('web')->user()->donation_amount - $order["total_price"];
//            $log["uid"] = auth('web')->user()->id;
//            $log["type"] = 3;
//            $log["money"] = $order["total_price"];
//            $log["wallet"] = $donation_amount;
//            $log["remarks"] = "";
//            $log["operation"] = "消费 订单号：".$order['order_sn'];
//            event(new \App\Events\WalletLogEvent($log));
//
//            $user["donation_amount"] = $donation_amount;
//
//        }elseif(auth('web')->user()->donation_amount < $order["total_price"] && auth('web')->user()->donation_amount != 0){
//            //赠送金不足，一起支付
//            $surplus = $order["total_price"] - auth('web')->user()->donation_amount;
//
//            if(auth('web')->user()->wallet < $surplus){
//                $this->result["status"] = 1;
//                $this->result["msg"] = "余额不足,请联系客服充值！";
//                return $this->result;
//            }
//
//            //赠送金抵扣
//            $log["uid"] = auth('web')->user()->id;
//            $log["type"] = 3;
//            $log["money"] = auth('web')->user()->donation_amount;
//            $log["wallet"] = 0;
//            $log["remarks"] = "赠送金抵扣￥"+auth('web')->user()->donation_amount+",余额抵扣￥"+$surplus;
//            $log["operation"] = "消费 订单号：".$order['order_sn'];
//            event(new \App\Events\WalletLogEvent($log));
//            //余额抵扣
//            $donation_amount = auth('web')->user()->wallet - $surplus;
//            $log["uid"] = auth('web')->user()->id;
//            $log["type"] = 0;
//            $log["money"] = $surplus;
//            $log["wallet"] = $donation_amount;
//            $log["remarks"] = "赠送金抵扣￥"+auth('web')->user()->donation_amount+",余额抵扣￥"+$surplus;
//            $log["operation"] = "消费 订单号：".$order['order_sn'];
//            event(new \App\Events\WalletLogEvent($log));
//
//            $user["donation_amount"] = 0;
//            $user["wallet"] = $donation_amount;
//        }elseif(auth('web')->user()->donation_amount == 0 && auth('web')->user()->wallet >= $order["total_price"]){
//            //没有赠送金，余额支付
//            $donation_amount = auth('web')->user()->wallet - $order["total_price"];
//            $log["uid"] = auth('web')->user()->id;
//            $log["type"] = 0;
//            $log["money"] = $order["total_price"];
//            $log["wallet"] = $donation_amount;
//            $log["remarks"] = "余额抵扣￥"+$donation_amount;
//            $log["operation"] = "消费 订单号：".$order['order_sn'];
//            event(new \App\Events\WalletLogEvent($log));
//            $user["wallet"] = $donation_amount;
//        }
//        //扣款
//        Member::where("id","=",auth('web')->user()->id)->update($user);
//
//        Orders::where("id","=",$id)->update(array("status"=>0,"pay_status"=>1,"pay_time"=>time(),"pay_type"=>2));
//
//        return $this->result;
    }

    /**
     * 获取订单号
     * @return json
     */
    public function getOrderSn()
    {
        $order_sn = date("ymdHis").rand(1000,9999);
        $count = Orders::where("order_sn",$order_sn)->count();
        if($count>0){
            $this->getOrderSn();
        }else{
            return $order_sn;
        }
    }


    /**
     * 删除
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function del(Request $request,$id)
    {
        $c = $request->input("c");
        //取消订单
        if($c == "cancel"){
            $updata["status"] = "-2";
            $msg = "取消成功";
        }
        //申请退款
        if($c == "refund"){
            $updata["status"] = "0";
            $updata["pay_status"] = "-1";
            $msg = "已提交申请";
        }
        //删除订单
        if($c == "del"){
            $updata["is_del"] = "-1";
            $msg = "删除成功";
        }
        //继续付款
        if($c == "pay"){
            $order = Orders::find((int)$id);
            $data["order_sn"] = $order->order_sn;
            $data["total_price"] = $order->total_price;
            //0:余额   1:赠送金
            $data["pay_type"] = $request->input("pay_type");

            $res = $this->payOrder($id,$data);

            $updata=array();
            if($res["status"] == 1){
                return redirect()->back()->withErrors($res["msg"]);
            }else{
                return redirect()->back()->withSuccess("付款成功");
            }
        }
        Orders::where("id","=",$id)->update($updata);
        return redirect()->back()->withSuccess($msg);
    }
}
